package com.danco.training.zaneuskaya.faces;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.danco.training.zaneuskaya.domain.City;
import com.danco.training.zaneuskaya.domain.Country;
import com.danco.training.zaneuskaya.domain.Message;
import com.danco.training.zaneuskaya.domain.User;
import com.danco.training.zaneuskaya.service.MessageService;
import com.danco.training.zaneuskaya.service.UserService;
import com.danco.training.zaneuskaya.service.exception.UserException;

/**
 * @author Zaneuskaya Aliaksandra
 *
 */
@Component
@Scope("session")
public class UserBean implements Serializable {

	private static final String USER_IS_SAVED_IN_DATABASE = "User is saved in database";

	private static final String USER_MAIN_FACES_REDIRECT_TRUE = "/user/main?faces-redirect=true";

	private static final String NO_LOGGED_IN_USER = "No logged in user ";

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = Logger.getLogger(UserBean.class);

	private User self;

	@Autowired
	private UserService userService;

	@Autowired
	private MessageService messageService;

	private List<Message> messageList;

	private Country country;

	private City city;

	public Country getCountry() {
		return country;
	}

	public void setCountry(Country country) {
		this.country = country;
	}

	public City getCity() {
		return city;
	}

	public void setCity(City city) {
		this.city = city;
	}

	public MessageService getMessageService() {
		return messageService;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}

	public List<Message> getMessageList() {
		return messageList;
	}

	public void setMessageList(List<Message> messageList) {
		messageList = messageService.getUserMessageList(self);
		this.messageList = messageList;
	}

	public User getSelf() {
		return self;
	}

	public void setSelf(User self) {

		this.self = self;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String saveUser() {

		self.setUserCountry(country);
		try {
			userService.createEntity(self);
		} catch (UserException e) {
			LOGGER.error(e.getMessage(), e);
		}

		LOGGER.info(USER_IS_SAVED_IN_DATABASE);

		return USER_MAIN_FACES_REDIRECT_TRUE;
	}

	public boolean isAdmin() {
		if (self != null) {
			return self.getAccount().isAdmin();
		}
		LOGGER.trace(NO_LOGGED_IN_USER);
		return false;
	}

	public boolean isUser() {
		if (self != null) {
			return self.getAccount().isUser();
		}
		LOGGER.trace(NO_LOGGED_IN_USER);
		return false;
	}

}
